#include <iostream>
#include <cstring>
#include <string>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
using namespace std;
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cerr << "Usage: " << argv[0] << "server_ip  server_port" << endl;
        return 1;
    }
    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "socket error" << endl;
        return 2;
    }
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());
    while (true)
    {
        string input;
        cout << "Please Enter# ";
        std::getline(cin, input);
        int n = sendto(sockfd, input.c_str(), input.size(), 0, (struct sockaddr *)&server, sizeof(server));
        if (n < 0)
        {
            cerr << "sendto error: " << strerror(errno) << endl;
            continue;
        }
        (void)n;
        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int m = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
        if (m < 0)
        {
            cerr << "recvfrom error: " << strerror(errno) << endl;
            continue;
        }
        else if (m == 0)
        {
            cout << "Connection closed by peer" << endl;
            break;
        }

        buffer[m] = 0;
        cout << buffer << endl;
    }
    //close(sockfd);
    return 0;
}